package com.artisan.domain.service;

import com.artisan.domain.dto.AccountDto;
import com.artisan.domain.dto.PageDto;
import com.artisan.domain.dto.RoleGroupDto;
import com.artisan.domain.dto.StartPageDto;
import com.artisan.domain.entity.MRoleGroup;
import com.artisan.domain.entity.MStartPage;
import com.artisan.domain.repositoryInterface.IRoleGroupRepository;
import com.artisan.domain.serviceInterface.IRoleGroupService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色组业务类
 */
@Service
public class RoleGroupService implements IRoleGroupService {
    @Autowired
    private IRoleGroupRepository roleGroupRepository;

    @Override
    public Page<RoleGroupDto> findList(int pageIndex, int pageSize) {

        Pageable pageable = new QPageRequest(pageIndex, pageSize);
        Page<MRoleGroup> page = this.roleGroupRepository.findList(pageable);
        List<RoleGroupDto> dtos = new ArrayList<>();
        page.getContent().forEach(
                model -> {
                    RoleGroupDto dto = new RoleGroupDto();
                    BeanUtils.copyProperties(model, dto);
                    dtos.add(dto);
                });

        Page<RoleGroupDto> result = new PageImpl(dtos,pageable,page.getTotalElements());
        return result;
    }

    @Override
    public boolean updateMenuIds(int id, String menuIds) {
        MRoleGroup model = this.roleGroupRepository.findById(id).get();
        model.setMenuIds(menuIds);
        this.roleGroupRepository.saveAndFlush(model);

        return true;
    }

    @Override
    public int add(RoleGroupDto dto) {
        MRoleGroup model = new MRoleGroup();
        model.setNumber("0");
        model.setName(dto.getName());
        model.setMenuIds("");
        model.setAddDate(System.currentTimeMillis());
        model.setStatus(1);
        model.setContent(dto.getContent());
        model = this.roleGroupRepository.saveAndFlush(model);

        return model.getId();

    }

    @Override
    public RoleGroupDto find(int id) {
        MRoleGroup model = this.roleGroupRepository.findById(id).get();
        RoleGroupDto dto = new RoleGroupDto();
        BeanUtils.copyProperties(model, dto);

        return dto;
    }

    @Override
    public boolean update(RoleGroupDto dto) {
        MRoleGroup model = this.roleGroupRepository.findById(dto.getId()).get();
        model.setName(dto.getName());
        model.setContent(dto.getContent());
        this.roleGroupRepository.saveAndFlush(model);
        return true;
    }
}
